package com.andaily.domain.developer.operation;

import com.andaily.domain.dto.user.UserFormDto;
import com.andaily.domain.team.TeamRepository;
import com.andaily.domain.user.Developer;
import com.andaily.domain.user.DeveloperRepository;
import com.andaily.web.context.BeanProvider;

/**
 * Date: 13-12-3
 *
 * @author Shengzhao Li
 */
public class UserFormPersister {

    private transient DeveloperRepository developerRepository = BeanProvider.getBean(DeveloperRepository.class);
    private transient TeamRepository teamRepository = BeanProvider.getBean(TeamRepository.class);

    private UserFormDto userFormDto;

    public UserFormPersister(UserFormDto userFormDto) {
        this.userFormDto = userFormDto;
    }

    public String persist() {
        if (userFormDto.isNewly()) {
            return saveUser();
        } else {
            return updateUser();
        }
    }

    private String updateUser() {
        final Developer existDeveloper = developerRepository.findByGuid(userFormDto.getGuid());
        existDeveloper.team(teamRepository.findByGuid(userFormDto.getTeamGuid()))
                .updateScrumTerm(userFormDto.getScrumTerm())
                .email(userFormDto.getEmail())
                .cellPhone(userFormDto.getCellPhone())
                .nickName(userFormDto.getNickName());
        existDeveloper.saveOrUpdate();
        return existDeveloper.guid();
    }

    private String saveUser() {
        Developer developer = userFormDto.toDomain();
        developer.team(teamRepository.findByGuid(userFormDto.getTeamGuid()));
        developer.saveOrUpdate();
        return developer.guid();
    }
}
